# _*_ coding: utf-8 _*_
# @Time:2023/11/28 9:25
# @Author:10917
# @File:depart_view.py
# 部门管理相关
from django.shortcuts import render, redirect
from tw591 import models
from tw591.utils.formlist import DepartModelForm
from tw591.utils.pagination import Pagination


def depart_list(request):
    """ 部门列表 """
    # queryset = models.Department.objects.all()
    # return render(request, "depart_list.html", {"queryset": queryset})

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["title__contains"] = search_data

    queryset = models.Department.objects.filter(**data_dict)

    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,

        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html(),  # 页码
    }
    return render(request, 'depart_list.html', context)


def depart_add(request):
    """ 部门添加 """
    if request.method == "GET":
        form = DepartModelForm()
        return render(request, "depart_add.html", {"form": form})

    # 将POST提交过来的数据 传给modelform组件自动判断
    form = DepartModelForm(data=request.POST)
    # 校验数据是否为空
    if form.is_valid():
        form.save()
        return redirect("/depart_list/")

    # 校验失败（在页面上显示错误信息）
    return render(request, 'depart_add.html', {"form": form})


def depart_edit(request, pid):
    """ 部门编辑 """
    if request.method == "GET":
        row_object = models.Department.objects.filter(id=pid).first()
        print(row_object)
        form = DepartModelForm(instance=row_object)
        return render(request, "depart_edit.html", {"form": form})

        # 获取用户提交的标题
    title = request.POST.get("title")
    models.Department.objects.filter(id=pid).update(title=title)
    # 重定向回部门列表
    return redirect("/depart_list/")


def depart_delete(request, pid):
    """ 部门删除 """
    models.Department.objects.filter(id=pid).delete()
    return redirect("/depart_list/")
